package org.siming.generator.processors;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @Author: yesiming
 * @Platform: Mac
 * @Date: 3:14 下午 2021/5/19
 */
public abstract class BaseAnnotationProcessor implements AnnotationProcessor {

    public void loadConfigKey() throws Exception {
        ResourceBundle resourceBundle = ResourceBundle.getBundle(fetchPropertiesFileName());
        Enumeration enumeration = resourceBundle.getKeys();
        while(enumeration.hasMoreElements()) {
            String key = (String) enumeration.nextElement();

            Class clazz = null;
            try {
                clazz = Class.forName(key);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                System.err.println("配置文件中内容: [" + key + "]不在项目中");
                continue;
            }

            try {
                clazz.newInstance();
            } catch (Exception e) {
                System.err.println("配置文件中内容: [" + key + "], newInstance失败");
                e.printStackTrace();
            }
        }
    }

    protected Map<String, String> doResource() throws Exception {
        Map<String, String> rsMap = new HashMap<>(2);

        // 配置文件名与生成器类名一致
        ResourceBundle resourceBundle = ResourceBundle.getBundle(fetchPropertiesFileName());
        Enumeration enumeration = resourceBundle.getKeys();
        while (enumeration.hasMoreElements()) {
            String key = (String) enumeration.nextElement();
            String value = resourceBundle.getString(key);
            rsMap.put(key, value);
        }

        return rsMap;
    }

    protected String fetchPropertiesFileName() throws Exception {
        String className = AnnotationProcessor.thisNameTL.get();
        if (StringUtils.isEmpty(className)) {
            throw new Exception("不可能异常闪现");
        }

        return className.replace(className.substring(0, 1), className.substring(0, 1).toLowerCase());
    }


    protected String fetchAnnotationName(String annotationPath) {
        if (StringUtils.isEmpty(annotationPath)) {
            return null;
        }
        String packageName = getPackage(annotationPath);
        String baseShortName = annotationPath
                .substring(packageName.length() + 1);


        return "@" + baseShortName;
    }

    protected static String getPackage(String baseQualifiedName) {
        int index = baseQualifiedName.lastIndexOf('.');
        return baseQualifiedName.substring(0, index);
    }

    public abstract void process(TopLevelClass topLevelClass) throws Exception;
}
